package com.common.groovy.adapter;

import cn.hutool.json.JSONObject;
import com.common.config.CommonApplicationConfig;
import com.common.exception.ErrorException;
import com.common.groovy.action.IAction;
import com.common.groovy.model.ActionModel;
import com.common.groovy.model.DataModel;
import com.common.model.SystemApplicationServiceModel;
import com.common.mysql.Where;
import com.common.sevice.SystemApplicationModelService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Description:
 * @Date: 2025/6/30 13:16
 */
@Component
public class GroovyModelAdapter {

    @Autowired
    private SystemApplicationModelService modelService;

    @Autowired
    private HttpServletRequest servletRequest;

    @Autowired(required = false)
    private Map<String, IAction> actionMap;

    @Autowired
    private CommonApplicationConfig applicationConfig;

    public Object call(String modelName, String actionName, Object args) throws ClassNotFoundException {
        String appId = servletRequest.getHeader("AppId");
        if (!StringUtils.hasText(appId)){
            appId = applicationConfig.getAppId();
        }
        SystemApplicationServiceModel systemApplicationModel = modelService.searchOne(Where.build().field("name").equal(modelName)
                .and().field("app_id").equal(appId)
                .and().field("del_flag").equal(0)
                .and().field("type").equal("3"));
        if (ObjectUtils.isEmpty(systemApplicationModel)) {
            throw new ErrorException("[" + modelName + "]模型不存在");
        }
        JSONObject data = systemApplicationModel.getData();
        if (ObjectUtils.isEmpty(data)){
            throw new ErrorException("[" + modelName + "]模型没定义具体data值");
        }
        DataModel dataModel = data.toBean(DataModel.class);
        List<ActionModel> actionList = dataModel.getAction();
        if (CollectionUtils.isEmpty(actionList)) {
            throw new ErrorException("[" + modelName + "]模型不存在action");
        }
        Map<String, ActionModel> actionModelMap = actionList.stream()
                .collect(Collectors.toMap(ActionModel::getName, Function.identity(), (k1, k2) -> k1));
        if (!actionModelMap.containsKey(actionName)){
            throw new ErrorException("[" + modelName + "]模型不存在actionName:[" + actionName + "]");
        }
        ActionModel actionModel = actionModelMap.get(actionName);
        //构建器
        if (actionMap.containsKey(actionModel.getType())) {
            IAction action = actionMap.get(actionModel.getType());
            return action.execute(actionModel, dataModel, args);
        }
        return null;
    }

}
